#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import date, timedelta
from tack.lib import json_app, content_headers, status_codes

day_display_format = '%d %b %Y'
week_display_format = '%A'
ymd_format = '%Y-%m-%d'


def today(environ, start_response):
    output = build_7day_info(date.today())
    return json_app(output)(environ, start_response)


def anyday(environ, start_response):
    disgroups = environ['dispatcher.groups']
    try:
        date_list = disgroups['date'].split('-')
        seed_day = date(int(date_list[0]), int(date_list[1]), int(date_list[2]))
    except:
        start_response(status_codes.error, content_headers.default_plain())
        return ['Error']
    output = build_7day_info(seed_day)
    return json_app(output)(environ, start_response)


def build_7day_info(seed_day):
    while seed_day.weekday() != 0:
        seed_day -= timedelta(days = 1)
    day_list = []
    for offset in [x for x in range(0,7)]:
        info = {}
        throwaway = seed_day + timedelta(days=offset)
        info['date'] = throwaway.strftime(ymd_format)
        info['display'] = throwaway.strftime(day_display_format).upper()
        info['dow'] = throwaway.strftime(week_display_format)
        day_list.append(info)
    output = {}        
    output['days'] = day_list
    output['today'] = date.today().strftime(ymd_format)
    output['display'] = date.today().strftime(day_display_format).upper()
    output['previous'] = (seed_day + timedelta(days=-7)).strftime(ymd_format)
    output['next'] = (seed_day + timedelta(days=7)).strftime(ymd_format)
    return output
    
